export function request(url, method, data, options = {}) {
  const baseUrl = globalThis.BASE_API;
  console.log('请求URL:', baseUrl + url);
  
  // 根据 options 中的 contentType 动态设置请求头
  const contentType = options.contentType || 'application/json';
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method: method,
      data: data,
      header: {
        'content-type': contentType,
        'Authorization': uni.getStorageSync('token') || ''
      },
      success: (res) => {
        console.log('请求成功:', res);
        resolve(res.data);
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(err);
      }
    });
  });
}

// 账号密码登录API（保持不变）
export const loginAPI = (userId, password) => {
  return request('/login', 'POST', { userId, password });
};

// 微信登录API（保持不变）
export const wechatLoginAPI = (code, encryptedData, iv) => {
  return request('/login/wechat', 'POST', { code, encryptedData, iv });
};

// 注册API（保持不变）
export const registerAPI = (userId, password) => {
  return request('/login/register', 'POST', { userId, password });
};

// 获取用户昵称（保持不变）
export const getNickNameAPI = (userId) => {
  return request(`/user/${userId}/nickname`, 'GET');
};

// 更新用户昵称（保持不变）
export const updateNickNameAPI = (userId, nickName) => {
  return request(`/user/${userId}/nickname`, 'PUT', { nickName });
};

// 新增：上传头像API，指定contentType为multipart/form-data
export const uploadAvatarAPI = (userId, file) => {
  const baseUrl = globalThis.BASE_API;
  const url = baseUrl + `/user/${userId}/avatar`;
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: url,
      filePath: file.uri,
      name: 'file',
      header: {
        'Authorization': uni.getStorageSync('token') || ''
      },
      success: (res) => {
        console.log('请求成功:', res);
        resolve(JSON.parse(res.data));
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(err);
      }
    });
  });
};